package com.behome.netty.netty_A.handler;

import com.behome.netty.netty_A.bean.ProtocolAPacket;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;


/**
 * @author bh_ljy
 * @description: 业务A解析器工厂类
 * @date: 2024/3/28 10:43
 */
@Slf4j
public class BusinessAHandlerFactory {

    public BusinessAHandlerFactory() {
    }

    public static BusinessAHandlerBase createBusinessHandler(ChannelHandlerContext ctx, ProtocolAPacket msg, String businessHandlerPackageName,int type) {
        if (ctx != null && msg != null) {
            if (StringUtils.isBlank(businessHandlerPackageName)) {
                return null;
            } else {
                String businessCmdStr = msg.getClass().getSimpleName();
                String handlerClassStr = businessHandlerPackageName + "." + businessCmdStr + "Handler";
                BusinessAHandlerBase handler = null;
                try {
                    Constructor<?> constructor = Class.forName(handlerClassStr).getConstructor(ChannelHandlerContext.class, ProtocolAPacket.class,int.class);
                    handler = (BusinessAHandlerBase) constructor.newInstance(new Object[]{ctx, msg,type});
                } catch (NoSuchMethodException | InvocationTargetException | IllegalArgumentException |
                         IllegalAccessException | InstantiationException | SecurityException var7) {
                    log.error("构造业务处理器时发生错误.", var7);
                } catch (ClassNotFoundException var9) {
                    log.warn("尚未提供名称为" + handlerClassStr + "的处理器来处理类型为" + businessCmdStr + "的业务指令.");
                }
                return handler;
            }
        } else {
            return null;
        }
    }
}
